//
//  AppDelegate.m
//  Rail
//
//  Created by hychen on 2018/2/24.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
#import "LoginViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "DeepLinkTool.h"
#import "DHGuidePageHUD.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:App_DeviceToken_Key];
    if (token){
        [MessageFactory getHttpHeader].device_token = token;
    }
    
    //初始化配置
    [[SetupConfiguration sharedTool] setupSetting];
    
    //注册推送
    [self registerRemotePushWithApplication:application];
//    [self initWithRemotePush:launchOptions];
    
    //通知
    [self addNotifications];
    
    //初始化控制器
    [self setupInitializeController];
    
    //引导图(在初始化控制器之后调用)
    [self setupGuidePage];
    
    //监听网络变化
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    return YES;
}

- (void)setupInitializeController {
    //初始化控制器
    UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    UIViewController *vc = nil;
    LoginViewController *loginVc = [[LoginViewController alloc] initWithComeFrom:LoginComeFromTypeNormal];
    vc = [[BaseNavigationController alloc] initWithRootViewController:loginVc];
    
    window.rootViewController = vc;
    [window makeKeyAndVisible];
    self.window = window;
}

- (BOOL)setupGuidePage {
    if ([[NSUserDefaults standardUserDefaults] objectForKey:App_GuidePage_Key]) {
        return NO;
    }
    DHGuidePageHUD *hud = [[DHGuidePageHUD alloc] dh_initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height) imageNameArray:@[@"0_1",@"0_2",@"0_3"] buttonIsHidden:NO];
    [[UIApplication sharedApplication].keyWindow addSubview:hud];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:App_GuidePage_Key];
    return YES;
}

#pragma mark - 通知
- (void)addNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:Notify_Login_Success object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(guidePageFadeSuccess) name:Notify_GuidePage_Fade_Success object:nil];
    
}

- (void)loginSuccess{
    self.tabBarController = [[SetupConfiguration sharedTool] setupTabBar];
    self.window.rootViewController = self.tabBarController;
}

- (void)guidePageFadeSuccess {
    //
}

#pragma mark 远程推送
- (void)registerRemotePushWithApplication:(UIApplication *)application{
    if (IOS10_bb) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate=self;
        UNAuthorizationOptions types10=UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
        [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                [[UIApplication sharedApplication] registerForRemoteNotifications];
                //点击允许
                //这里可以添加一些自己的逻辑
            } else {
                //点击不允许
                //这里可以添加一些自己的逻辑
            }
        }];
    }
    else if(IOS8_bb) {
        if([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            //注册推送,用于iOS8以及iOS8之后的系统
            UIUserNotificationSettings*settings = [UIUserNotificationSettings
                                                   
                                                   settingsForTypes:(UIUserNotificationTypeBadge|
                                                                     
                                                                     UIUserNotificationTypeSound|
                                                                     
                                                                     UIUserNotificationTypeAlert)
                                                   
                                                   categories:nil];
            
            [application registerUserNotificationSettings:settings];
            
            [application registerForRemoteNotifications];
            
        }
    }
    else {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
        [application registerForRemoteNotifications];
    }
    
}

//- (void)initWithRemotePush:(NSDictionary *)launchOptions{
//    if (launchOptions && launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]){
//        [self handlePushMessage:launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]];
//    }
//
//    [UMessage startWithAppkey:UmengPushKey launchOptions:launchOptions httpsEnable:YES];
//    [UMessage registerForRemoteNotifications];
//    //iOS10
//    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//    center.delegate=self;
//    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
//    [center requestAuthorizationWithOptions:types10     completionHandler:^(BOOL granted, NSError * _Nullable error) {
//        if (granted) {
//            //点击允许
//        } else {
//            //点击不允许
//        }
//    }];
//    [UMessage setLogEnabled:YES];
//}
//
//- (void)handlePushMessage:(NSDictionary*)msg{
//    //    NSDictionary *content = msg
//    [UIApplication sharedApplication].applicationIconBadgeNumber = 1;
//
//    YMPushModel *model = [YMPushModel new];
//    NSDictionary *contentDict = [[msg objectForKey:@"aps"] objectForKey:@"alert"];
//    if (contentDict && [contentDict isKindOfClass:[NSDictionary class]]) {
//        model.title = [contentDict objectForKey:@"title"]?:@"";
//        model.body = [contentDict objectForKey:@"body"]?:@"";
//        model.subtitle = [contentDict objectForKey:@"subtitle"]?:@"";
//    }
//
//    NSString *content = model.body;
//    if (model == nil) {  //ios10之前model为nil
//        content = msg[@"aps"][@"alert"];
//    }
//
//    NSString *type = msg[@"msgtype"];
//    NSString *opid = msg[@"opid"];
//
//    if (opid) {
//
//        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//        NSString *timeString = [formatter stringFromDate:[NSDate date]];
//        InformationModel *infoModel = [[InformationModel alloc] initWithTitle:model.title?:@"" content:content?:@"" time:timeString type:(BusRemoteType)[type integerValue] opid:opid];
//
//        NSMutableArray *array = nil;
//        if (![GlobalManage sharedTool].remoteArray.count) {
//            array = [NSMutableArray array];
//        }else{
//            array = [GlobalManage sharedTool].remoteArray;
//        }
//
//        if (infoModel) {
//            [array insertObject:infoModel atIndex:0];
//            [self.tabBarController.tabBar showBadgeOnItmIndex:2 tabbarNum:4];
//        }
//        [GlobalManage sharedTool].remoteArray = array;
//    }
//
//    [[NSNotificationCenter defaultCenter] postNotificationName:Notify_Remote_Information object:nil userInfo:nil];
//
//}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    BOOL result = [[DeepLinkTool sharedTool] handleDeepLinkUrl:url];
    return result;
}
@end
